﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace ClientNetwork
{
    public class Client
    {
        public static String Connect(String serverIP, String message)
        {
            String output = "";

            try
            {
                // Create a TcpClient.
                // The client requires a TcpServer that is connected
                // to the same address specified by the server and port
                // combination.server
                Int32 serverPort = 13;
                TcpClient client = new TcpClient(serverIP, serverPort);

                // Translate the passed message into Unicode and store it as a byte array.
                Byte[] data = new Byte[256];
                data = System.Text.Encoding.Unicode.GetBytes(message);

                // Get a client stream for reading and writing.
                // Stream stream = client.GetStream();
                NetworkStream dataStream = client.GetStream();

                // Send the message to the connected TcpServer. 
                dataStream.Write(data, 0, data.Length);

                output = "Sent: " + message;
                //MessageBox.Show(output);

                // Buffer to store the response bytes.
                data = new Byte[256];

                // String to store the response Unicode representation.
                String responseData = String.Empty;

                // Read the first batch of the TcpServer response bytes.
                Int32 bytes = dataStream.Read(data, 0, data.Length);
                responseData = System.Text.Encoding.Unicode.GetString(data, 0, bytes);
                output = "Received: " + responseData;
                //MessageBox.Show(output);
                return output;

                // Close everything.
                dataStream.Close();
                client.Close();
            }
            catch (ArgumentNullException e)
            {
                output = "ArgumentNullException: " + e;
                //MessageBox.Show(output);
                return output;
            }
            catch (SocketException e)
            {
                output = "SocketException: " + e.ToString();
                //MessageBox.Show(output);
                return output;
            }
        }
    }
}
